import subprocess
import re
import os
import base64
try:
            data = "helloworld".encode('utf-8')      
            private_key = "MIGIAgEAMBQGCCqBHM9VAYItBggqgRzPVQGCLQRtMGsCAQEEIOAIGFYnh+iF2nX3\nsfs6/DZ+wTH5FeedlIDT7AJNht0goUQDQgAE8iURO/3F/dOEVEJ7+6UgVsmHxow1\n5FGr3eeM1SDI+AcjrEKZF93mvWbzc7Ds0CRh4/THeQakgfeVF1epZO+feA==".encode('utf-8')
            private_key_pem = f"-----BEGIN PRIVATE KEY-----\n{private_key.decode()}\n-----END PRIVATE KEY-----".encode('utf-8')

            with open("data.txt", "wb") as file:
                file.write(data)

            with open("sm2_private_key.pem", "wb") as file:
                file.write(private_key_pem)

            cmd = "openssl dgst -sm3 -sign sm2_private_key.pem -out signature.bin data.txt"
            result = subprocess.run(cmd, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

            with open("signature.bin", "rb") as file:
                signature = file.read()
                signature_base64 = base64.b64encode(signature).decode('utf-8')

            os.remove("data.txt")
            os.remove("sm2_private_key.pem")
            os.remove("signature.bin")

            print(signature_base64)
except subprocess.CalledProcessError as e:
    print("标准输出：", e.stdout.decode())
    print("错误输出：", e.stderr.decode())
except Exception as e:
            print(str(e))